package com.gg.ai.controller;

import com.gg.ai.pojo.ChatHistory;
import com.gg.ai.pojo.JsonVariable;
import com.gg.ai.pojo.Result;
import com.gg.ai.pojo.TextDTO;
import com.gg.ai.service.ChatHistoryService;
import com.gg.ai.service.UserService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.*;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@RestController
@ResponseBody
@RequestMapping("/java/api/v1")
public class AiController {
    @Autowired
    private UserService userService;
    @Autowired
    private ChatHistoryService chatHistoryService;
    private final Gson gson = new Gson();

    @GetMapping("/chat")
    public Result getSession(@RequestParam Integer userId, @RequestParam String sessionId) {
        Map<String,Object> requestMap = new HashMap<>();
        ChatHistory chatHistory = chatHistoryService.queryList(userId, sessionId);
        JsonVariable.historyList = chatHistory.getHistoryList();
        if (JsonVariable.historyList == null) {
            return Result.success();
        }
        TextDTO[] textDTOS = gson.fromJson(JsonVariable.historyList, TextDTO[].class);

        // 迭代获取属性和对应的值
        Class<?> clazz = chatHistory.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(chatHistory);
//                System.out.println("属性名：" + field.getName() + "，属性值：" + value);

                if (field.getName().equals("historyList")) {
                    requestMap.put(field.getName(),textDTOS);
                } else {
                    requestMap.put(field.getName(),value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
       return Result.success(requestMap);
    }

    @GetMapping("/chat/userid")
    public Result getSessionByUserId(@RequestParam Integer userId) {
        List< Map<String,Object>> requestList = new ArrayList<>();
        List<ChatHistory> chatHistoryList = chatHistoryService.getSessionByUserId(userId);
        for (ChatHistory chatHistory : chatHistoryList) {
            TextDTO[] textDTOS = gson.fromJson(chatHistory.getHistoryList(), TextDTO[].class);
            // 迭代获取属性和对应的值
            Map<String,Object> requestMap = new HashMap<>();

            Class<?> clazz = chatHistory.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    Object value = field.get(chatHistory);
//                    System.out.println("属性名：" + field.getName() + "，属性值：" + value);
                    if (field.getName().equals("historyList")) {
                        requestMap.put(field.getName(),textDTOS);
                    } else {
                        requestMap.put(field.getName(),value);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            requestList.add(requestMap);
        }
        return Result.success(requestList);
    }

    @GetMapping("/chat/{id}")
    public Result getSessionById(@PathVariable Integer id) {
        Map<String,Object> requestMap = new HashMap<>();
        ChatHistory sessionById = chatHistoryService.getSessionById(id);
        if (sessionById == null) {
            List<Object> list= new ArrayList<>();
            return Result.success(list);
        }
        JsonVariable.historyList = sessionById.getHistoryList();
        System.out.println(JsonVariable.historyList);

        TextDTO[] textDTOS = gson.fromJson(String.valueOf(sessionById.getHistoryList()), TextDTO[].class);


        // 迭代获取属性和对应的值
        Class<?> clazz = sessionById.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(sessionById);
//                System.out.println("属性名：" + field.getName() + "，属性值：" + value);

                if (field.getName().equals("historyList")) {
                    requestMap.put(field.getName(),textDTOS);
                } else {
                    requestMap.put(field.getName(),value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return Result.success(requestMap);
    }

    @PostMapping("/chat/{userId}")
    public Result insertSession(@PathVariable Integer userId) {
        return  chatHistoryService.insertSession(userId)? Result.success() : Result.error(400,"添加会话失败");
    }

    @PutMapping("/chat/{id}")
//    List<Map<String,Object>> historyList
    public Result updateHistory(@PathVariable Integer id, @RequestBody List<Map<String,Object>> historyList) {
        return  chatHistoryService.updateHistoryList(id,historyList)? Result.success() : Result.error(400,"会话历史更新失败");
    }

    @DeleteMapping("/chat/{id}")
    public Result deleteSession(@PathVariable Integer id) {
        return chatHistoryService.deleteSession(id) ? Result.success() : Result.error(400,"会话历史删除失败");
    }
}
